package com.augurit.wf.app.document.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springside.modules.orm.Page;

import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.wf.app.document.converter.DocConvert;
import com.augurit.wf.app.document.dao.DocCategoryDao;
import com.augurit.wf.app.document.dao.DocumentDao;
import com.augurit.wf.app.document.entity.DocCategory;
import com.augurit.wf.app.document.entity.Document;
import com.augurit.wf.app.document.service.IdocCategory;
import com.augurit.wf.app.document.utils.DocTreeNode;
import com.augurit.wf.app.document.utils.DozerUtils;
import com.augurit.wf.app.document.utils.TreeUtil;
import com.augurit.wf.app.document.utils.Version;
import com.augurit.wf.app.document.web.form.DocCategoryForm;
import com.augurit.wf.app.document.web.form.DocumentForm;


@Service
@Transactional
public class DocCategoryImpl implements IdocCategory{
	
	@Autowired(required=true)
	private DocCategoryDao docCategoryDao;
	
	@Autowired
	private DocumentDao docDao;

	public List<DocTreeNode> buildTree(Long id, String version) {
		List<DocTreeNode> nodes = new ArrayList<DocTreeNode>();
		if(id != null && version != null){
			//目录分类有子分类
			List<DocCategoryForm> list = this.getChildrenCategory(id, version);
			if(list != null && list.size()>0){
				nodes.addAll(TreeUtil.convertDocCategoryForms2TreeNodes(list));
				
			}
			//文档
			List<DocumentForm> docList =  this.getChildrenDocs(id, version);
			if(docList != null && docList.size()>0){
				nodes.addAll(TreeUtil.convertDocumentForms2TreeNodes(docList));}
				
		}
		return nodes;
	}
	
	
	private List<DocCategoryForm> getChildrenCategory(Long id, String version){
		List<DocCategory> entitys = this.docCategoryDao.getChildrenCategory(id,version);
		if(entitys != null){
			List<DocCategoryForm> result = DozerUtils.map(entitys, DocCategoryForm.class);
			return result;
		}
		return null;
		
	}
	
	public List<DocCategoryForm> getCategoryUnderGivenCategory(Long pid, String childCatName){
		List<DocCategory> entitys = this.docCategoryDao.getCategoryUnderGivenCategory(pid,childCatName);
		if(entitys != null){
			List<DocCategoryForm> result = DozerUtils.map(entitys, DocCategoryForm.class);
			return result;
		}
		return null;
	}
	
	private  List<DocumentForm> getChildrenDocs(Long id,String version){
		List<Document> entitys=this.docDao.getChildrenDocs(id,version);
		if(entitys != null){
			List<DocumentForm> result = DozerUtils.map(entitys, DocumentForm.class);
			return result;
		}
		return null;
	}


	public boolean catUpdate(Long id, String text) {
		
		DocCategory category=docCategoryDao.findUniqueBy("id", id);
		if(category !=null&& text !=null && text.length()>0) {
			  category.setName(text);
			  docCategoryDao.save(category);
		      return true;
		}else {
			return false;
		}
		
		
		
	}


	public boolean catSave(DocCategoryForm form) {
		if(form!=null ){
			DocCategory cat =new DocCategory();
			cat.setName(form.getName());
			cat.setPid(form.getPid());
			cat.setVersion(form.getVersion());
			docCategoryDao.save(cat);
			cat.setInx(cat.getId().intValue());//创建的目录的序号都和主键一致
			docCategoryDao.save(cat);
			form.setId(cat.getId());
			return true;
		}else{
			return false;
		}
		
		
	}


	public Page<DocumentForm> searchDocuments(Page<DocumentForm> page, DocumentForm form) {
		Page<Document> pg =PageUtils.newPageInstance(page);
		StringBuffer hql= new StringBuffer("from Document doc where 1=1");
		List values = new ArrayList();
		if(form != null){
            if(form.getCid()!=null){
				Long unitid =form.getCid();
				hql.append(" and doc.cid = ?");
				values.add(unitid);
			}
			if(StringUtils.isNotBlank(form.getName())){
				hql.append(" and doc.name like ?");
				values.add("%" + form.getName() + "%");
			}
			if(StringUtils.isNotBlank(form.getFileName())){
				hql.append(" and doc.filename like ?");
				values.add("%" + form.getFileName() + "%");
			}
			if(StringUtils.isNotBlank(form.getDocType())){
				hql.append(" and doc.doctype like ?");
				values.add("%" + form.getName() + "%");
			}
			if(StringUtils.isNotBlank(form.getStatus())){
				hql.append(" and doc.status like ?");
				values.add("%" + form.getStatus() + "%");
			}
		}
		//System.out.println("oder:"+page.getOrderBy());
		pg.setOrderBy(page.getOrderBy());
		hql.append(HqlUtils.buildOrderBy(pg, "doc"));
		String testSql ="select * from doc_document_detail";
		pg=docDao.findPage(pg, hql.toString(), values);
		List<Document> list=pg.getResult();
		List<DocumentForm> list2=DocConvert.convertEntityListtoFormList(list);
		PageUtils.copy(pg, list2, page);
		return page;
	}

    //根据目录名称查找目录的id
	public Long findByName(String name) {
		DocCategory category=docCategoryDao.findBy("name", name).get(0);
		if(category != null) return category.getId();
		else return null;
	}


	public void saveDoc(DocumentForm form) {
		// TODO Auto-generated method stub
		Assert.notNull(form);
		Document entity = null;
		if(form.getId() != null){
			entity = docDao.get(form.getId());
		}else{
			entity = new Document();
		}
		DozerUtils.map(form, entity);
		docDao.save(entity);
		form.setId(entity.getId());
		
	}


	public String findDocUrl(Long id) {
		String url=docDao.findUniqueBy("id", id).getUrl();
		return url;
	}


	public String findDocFileName(Long id) {
		String url=docDao.findUniqueBy("id", id).getFileName();
		return url;
	}


	public List<DocCategoryForm> findAllCat() {
		List<DocCategory> list=docCategoryDao.getAll();
		List<DocCategoryForm> list2=DocConvert.convertCats2Formlist(list);
		return list2;
	}


	public Boolean deletedocs(String path,Long... ids) {
		Boolean flag =null;
		if(ids!=null&& ids.length>0){
			for(int i=0;i<ids.length;i++){
				flag=deletedoc(path,ids[i]);
				if(!flag)//一有错就报错误
					break;
			}

		}
		return flag;
		
			
		   
	}
	
	private Boolean deletedoc(String path,Long id){
		Boolean flag =null;
		Document document=docDao.get(id);
		String url=document.getUrl();
		String myurl=path+url.substring(7);
	    File newFile =new File(myurl);
	   //不存在的文件也把相应的记录给删除
	    if(!newFile.exists()){
	    	docDao.delete(id);
	    	flag=true;
	    	return flag;
	    }else{
	    //判断文件是否正被下载
	    if(newFile.renameTo(newFile)){
	    	newFile.delete();
	    	docDao.delete(id);
	    	flag= true;
	    }else{
	    	flag= false;
	    }
	    return flag;
	    }
		
	}


	public DocumentForm findDoc(Long id) {
		if(id!=null){
			Document document=docDao.findUniqueBy("id", id);
			DocumentForm form=DocConvert.convertToForm(document);
			return form;
		}
		return null;
	}


	public String findCatName(Long id) {
		if(id!=null){
			return docCategoryDao.findUniqueBy("id", id).getName();
		}
		return null;
	}

	//删除以该目录为父目录的所有子目录(包括子目录下所有的子目录）以及文档
	public void deleteDir(String path,Long id) {
		
	    deleteCat(path,id);
		
	}
	
	//递归查找子目录
	public void deleteCat(String path, Long id){

		List<DocCategory> listDir=docCategoryDao.findBy("pid", id);
		System.out.println("listDir:"+listDir);
		if(listDir==null || listDir.size()==0){
			
			docCategoryDao.delete(id);
			List<Document> list2=docDao.findBy("cid", id);
			if(list2!=null && list2.size()>0){
				for(int i=0;i<list2.size();i++){
					this.deletedoc(path,list2.get(i).getId());
				}
			}
		}else if(listDir.size()==1){
			docCategoryDao.delete(id);
			List<Document> list2=docDao.findBy("cid", id);
			if(list2!=null && list2.size()>0){
				for(int i=0;i<list2.size();i++){
					this.deletedoc(path,list2.get(i).getId());
				}
			}
			docCategoryDao.delete(listDir.get(0));
			List<Document> listdoc=docDao.findBy("cid", listDir.get(0).getId());
			if(listdoc!=null && listdoc.size()>0){
				Iterator<Document> it =listdoc.iterator();
				while(it.hasNext()){
					this.deletedoc(path,it.next().getId());
				}
			}
			docCategoryDao.delete(listDir.get(0));
		}else{
			Iterator<DocCategory> iterator=listDir.iterator();
			while(iterator.hasNext()){
				this.deleteCat(path,iterator.next().getId());
			}
	
		}
		
		
		
	}
	/**
	 * 
	 */
	public List<DocumentForm> findDocument(String version,String status) {
		if(version!=null){
			List<Document> documents=docDao.findDocs(version,status);
			if(documents != null && documents.size() > 0){
				List<DocumentForm> documentForms = DozerUtils.map(documents, DocumentForm.class);
				return documentForms;
			}
		}
		return null;
	}
	
	//获取所有文档的版本
	public List<Version> getVersionList(){
		return docCategoryDao.getVersionList();
	}
	
}
